<template>
  <div>
    <Breadcrumb :title="subTitle" :opt-data="templateOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="templateData"
          :custom-empty="true"
          @pageChanged="getTemplateData"
          @sizeChanged="getTemplateData"
          @filterChange="getTemplateData">
          <div slot="customOpts">
            <div>
              <el-tooltip :open-delay="300" content="导入房间模板配置" placement="top">
                <el-upload action="" :before-upload="importTemplate"
                           class="display-inline-block mar-lft-5">
                  <el-button class=" table-filter-opt-btn ">
                    <i class="iconfont icon-bendidaoru font-size-16"></i>
                  </el-button>
                </el-upload>
              </el-tooltip>
            </div>
          </div>
          <EmptyContent slot="empty" :opt-data="templateOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog v-loading="templateFormLoading" :visible.sync="showTemplateDialog" :append-to-body="true" :close-on-click-modal="false"
                 :title="isEditTemplate ? '修改房间模板配置' : '新增房间模板配置'" width="750px" top="100px">
        <el-form :ref="templateFormRef" :model="templateForm" :rules="templateFormRules" size="medium"
                 label-width="80px">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="房间名称" prop="roomName">
                <el-input v-model="templateForm.roomName" placeholder="请填写房间名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间类别" prop="roomType">
                <el-select v-model="templateForm.roomType" :filterable="true" :clearable="true"
                           placeholder="请选择房间类别" size="small" class="width-100">
                  <el-option v-for="project in roomTypeArray" :key="project.value" :label="project.label"
                             :value="project.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="平板类型" prop="padType">
                <el-select v-model="templateForm.padType" placeholder="请选择平板类型" size="small" :disabled="isEditTemplate"
                           class="width-100" clearable>
                  <el-option v-for="(item,index) in padTypeArray" :label="item.label" :value="item.value" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12"  v-if="!templateForm.padModelId && isEditTemplate">
              <el-form-item label="平板型号">
                <el-input v-model="templateForm.device" placeholder="请填写平板型号" class="width-100">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item label="平板型号">
                <el-select v-model="templateForm.padModelId" placeholder="请选择平板型号" size="small"
                           class="width-100" clearable filterable @change="selectPad">
                  <el-option v-for="(item,index) in ipadConfig" :label="`${item.label}-(${item.window.width}*${item.window.height})`" :value="item.value" :key="index">
                    <span>{{item.label}}</span>
                    <span class="mar-lft font-color-warning">({{item.window.width}}*{{item.window.height}})</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="分控版本" prop="ezControlVersion">
                <el-input v-model="templateForm.ezControlVersion" placeholder="请填写分控版本"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" v-if="!templateForm.padModelId && isEditTemplate">
            <el-col :span="12">
              <el-form-item label="页面宽度">
                <el-input-number v-model="templateForm.window.width" controls-position="right"
                                 class="width-100">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="页面高度">
                <el-input-number v-model="templateForm.window.height" controls-position="right"
                                 class="width-100">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="isEditTemplate" label="版本号">
            <el-input v-model="templateForm.version" placeholder="请填写版本号"></el-input>
          </el-form-item>
          <el-form-item label="主题色">
	          <ThemePicker v-model="templateForm.theme"></ThemePicker>
          </el-form-item>
          <el-form-item label="预览图" v-if="isEditTemplate">
            <ImageUpload :preview-type="previewType.room" :image-list="templateForm.previewImages"></ImageUpload>
          </el-form-item>
	        <el-form-item prop="remarks" label="备注">
		        <el-input v-model="templateForm.remarks" type="textarea" placeholder="请填写备注"></el-input>
	        </el-form-item>
          <div class="mar-top text-align-right">
            <el-button type="info" @click="showTemplateDialog = false">取消</el-button>
            <el-button type="primary" @click="templateFormSubmit">提交</el-button>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {deepCopyWithJson, JSONParse, getUserInfo, generateUID, editorConfigPreview, downloadFileApi} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import templateTableCfg from "../../../config/table/roomTemplate";
  import EZTable from '../../../components/table/EZTable.vue';
  import {assetBaseUrl} from "@/config/env";
  import {routerMeta} from "@/router/routerMeta";
  import {
		userRoleCfg,
	  roomTypeArray,
	  uploadPreviewType,
	  padTypeArray,
	  globalReserveOptions,
	  globalVariableOptions,
	  globalGuideOptions
	} from "@/config/common";
  import FileSaver from 'file-saver';
  import ThemePicker from "@/components/IDE/ThemePicker.vue";
  import ImageUpload from '@/components/ImageUpload.vue';

  export default {
    name: "TemplateManagement",
    components: {
      EZTable, ThemePicker, ImageUpload
    },
    data() {
      return {
        userRoleCfg: userRoleCfg,
        userInfo: getUserInfo(),
        previewType: uploadPreviewType,
        tableId: tableIdConfig.roomTemplate,
        tableLoading: true,
        tableHdl: null,
        templateData: [],
        selectedTemplate: {},
        isEditTemplate: false,
        showTemplateDialog: false,
        templateFormLoading: false,
        templateFormRef: 'templateFormRef',
        templateForm: {
          roomName: "",
          window: {width: 1024, height: 768},
          device: "",
          version: "",
          isAdvancedProgram: '',
          isEnvControl: '',
          roomType: '',
          ezControlVersion: '',
          previewImages: [],
          theme: 'theme1',
	        remarks: '',
          globalVar:[],
          roomScenes:[],
          homePageId:'',
          padModelId:'',
          padType:''
        },
        templateFormRules: {
          roomName: [
            {required: true, message: '请填写房间名称', trigger: ['blur', 'change']}
          ],
          roomType: [
            {required: true, message: '请选择房间类别', trigger: ['blur', 'change']}
          ],
          padType: [
            {required: true, message: '请选择平板类型', trigger: ['blur', 'change']}
          ],
        },
        action: `${assetBaseUrl}/roomConfig/upload`,
        roomTypeArray: roomTypeArray,
        fileBaseUrl: `${assetBaseUrl}/file/download/`,
        detailConfig: {},
        subTitle: '',
        ipadConfig:[],
        padTypeArray: padTypeArray,
      }
    },
    computed: {
      templateOptData() {
        return [
          {
            type: 'btn',
            label: '管理公共图片',
            icon: 'icon-upload',
            callback: () => {
              this.$router.push({name: routerMeta.commonAsset.name});
            }
          },
          {
            type: 'btn',
            label: '新增房间模版',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.subTitle = this.$route.query.subTitle;
      this.initTableConfig();
      this.initTemplateForm();
      this.getTemplateData();
      this.getAllIpad() ;//拿平板型号数据
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, templateTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const template = deepCopyWithJson(data);
          const {
            _id, roomName, roomType, window: padWindow = {}, previewImages = [], theme,
            device, version, ezControlVersion, isEnvControl, isAdvancedProgram,globalVar=[],
            roomScenes=[], homePageId='',padModelId='',padType=''
          } = template;
          this.selectedTemplate = template;
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showTemplateDialog = true;
              this.isEditTemplate = true;
              this.templateForm = {
                _id: _id,
                roomName: roomName,
                window: {width: padWindow.width, height: padWindow.height},
                device: device,
                version: version,
                isEnvControl: isEnvControl,
                isAdvancedProgram: isAdvancedProgram,
                roomType: roomType,
                ezControlVersion: ezControlVersion,
                previewImages: previewImages,
                theme: theme || 'theme1',
                globalVar:globalVar,
                roomScenes:roomScenes,
                homePageId:homePageId,
                padModelId:padModelId,
                padType:padType
              };
              break;
            case tableOptBtnConfig.preview.type: {
              //预览
              editorConfigPreview({type: 'room', roomId: _id});
              break;
            }
            case tableOptBtnConfig.select.type:
              //编辑
              window.open(this.$router.resolve({
                name: routerMeta.roomEditor.name,
                params: {rid: _id}
              }).href, '_blank');
              break;
            case tableOptBtnConfig.copy.type:
              this.copyTemplateSubmit(template);
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteTemplate(template);
              break;
            case tableOptBtnConfig.export.type:
              this.exportTemplate(template);
              break;
            case tableOptBtnConfig.exportZip.type:
              this.exportPage(template);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      exportPage(room) {
        this.$confirm(`是否导出资源包附带设备元数据(旧版本分控请选择不导出)?`, "提示", {
          distinguishCancelAndClose: true,
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        }).then(() => {
          downloadFileApi(`${assetBaseUrl}/roomConfig/download/config/assets`, {_id: room._id,exportMetadata:true});
        }).catch((action) => {
          if( action === 'cancel'){
          downloadFileApi(`${assetBaseUrl}/roomConfig/download/config/assets`, {_id: room._id,exportMetadata:false});
          }
        });
      },
      // 处理图片
      getImage(images) {
        if (!images) return [];
        // 新增代码
        const imageArray = [];
        images.forEach((item) => {
          const imageObj = {};
          imageObj.url = `${this.fileBaseUrl}${item}`;
          imageObj.name = item;
          imageArray.push(imageObj);
        });
        return imageArray;
      },
      initTemplateForm() {
        this.templateForm = {
          roomName: "",
          window: {width: 1024, height: 768},
          device: "",
          version: "",
          isEnvControl: '',
          isAdvancedProgram: '',
          roomType: '',
          ezControlVersion: '',
          previewImages: [],
          theme: 'theme1',
          globalVar:[],
          roomScenes:[],
          homePageId:'',
          padModelId:'',
          padType:''
        };
      },
      resetTemplateForm() {
        this.initTemplateForm();
        const templateForm = this.$refs[this.templateFormRef];
        templateForm && templateForm.resetFields();
      },
      getTemplateData() {
        this.tableLoading = true;
        const selector = {isTemplate: true};
        const tableParam = this.tableHdl.assembleTableParam();
        API.room.roomList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.templateData = data.map(d => {
            return {
              ...d,
              size: `<span class="font-color-success">${d.window.width} x ${d.window.height}</span>`,
            }
          });
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err);
          this.tableLoading = false;
        });
      },
      clickCreateBtn() {
        this.resetTemplateForm();
        this.isEditTemplate = false;
        this.showTemplateDialog = true;
      },
      templateFormSubmit() {
        this.$refs[this.templateFormRef].validate((valid) => {
          if (!valid) return;
          this.templateFormLoading = true;
          const params = {isTemplate: true, ...this.templateForm};
          if (this.isEditTemplate) {
            API.room.roomEdit(params).then((resp) => {
              this.templateFormLoading = false;
              this.showTemplateDialog = false;
              this.$message({
                message: "房间模板配置编辑成功!",
                type: "success",
                duration: 1500,
              });
              this.getTemplateData();
            }).catch((err) => {
              this.templateFormLoading = false;
              console.log("err: ", err);
            });
          } else {
            params.roomScenes = [
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'SystemOn',
                name: '开启系统'
              },
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'SystemOff',
                name: '关闭系统'
              },
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'LocalConference',
                name: '本地会议'
              },
              {
                key: `roomScenes-${generateUID()}`,
                sceneId: 'VideoConference',
                name: '视频会议'
              },
            ];
						switch (params.padType) {
						  case 'control':
							  params.globalVar = globalVariableOptions;
						    break;
						  case 'reserve':
							  params.globalVar = globalReserveOptions;
						    break;
						  case 'guidance':
							  params.globalVar = globalGuideOptions;
						    break;
						  default:
						    break;
						}
            API.room.roomAdd(params).then((resp) => {
              this.templateFormLoading = false;
              this.showTemplateDialog = false;
              this.$message({
                message: "房间模板配置新增成功!",
                type: "success",
                duration: 1500,
              });
              this.getTemplateData();
            }).catch((err) => {
              this.templateFormLoading = false;
              console.log("err: ", err);
            });
          }
        });
      },
      // 复制
      copyTemplateSubmit(row) {
        this.$confirm(`确定要复制【${row.roomName}】的房间吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const params = {_id: this.selectedTemplate._id};
          API.room.roomClone(params).then((resp) => {
            this.$message({
              message: "房间模板配置复制成功!",
              type: "success",
              duration: 1500,
            });
            this.getTemplateData();
          }).catch((err) => {
            console.log("err: ", err);
          });
        }).catch(() => {
        });

      },
      //删除
      deleteTemplate(row) {
        this.$confirm(`确定要删除【${row.roomName}】的房间模板配置吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          API.room.roomDelete({roomId: row._id}).then((resp) => {
            this.$message({
              message: "房间模板配置删除成功!",
              type: "success",
              duration: 1500,
            });
            this.getTemplateData();
          }).catch((err) => {
            console.log("err: ", err);
          });
        }).catch(() => {
        });
      },
      //导出房间的资源
      exportTemplate(row) {
        this.$confirm(`确定要导出【${row.roomName}】的房间模板配置吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          API.room.roomExport({roomId: row._id || ''}).then(resp => {
            this.detailConfig = resp.data;
            const {room} = resp.data;
            const {roomName = '房间'} = room;
            FileSaver.saveAs(new Blob([JSON.stringify(this.detailConfig)]), `${roomName}_模板配置.json`);
          }).catch(err => {
          });
        }).catch(() => {
        });
      },
      //导入配置
      importTemplate(file) {
        let fileReader = new FileReader();
        this.tableLoading = true;
        fileReader.onload = async (e) => {
          try {
            const params = JSONParse(e.target.result || "{}");
            params.room.isTemplate = true;
						delete params.room['projectId'];
            API.room.roomImport(params).then(() => {
              this.tableLoading = false;
              this.$message({
                message: "导入成功!",
                type: "success",
                duration: 1500,
              });
              this.getTemplateData();
            }).catch((err) => {
              this.tableLoading = false;
              console.log("err: ", err);
            });
          } catch (err) {
            console.log(`配置导入失败: ${err.message}`);
            this.tableLoading = false;
          }
        };
        fileReader.readAsText(file);
        return false;
      },
      getAllIpad(){
        API.ipad.ipadAll().then(result => {
          const {data = []} = result;
          this.ipadConfig = data
        }).catch(err => {
          console.log('err', err);
          this.tableLoading = false;
        });
      },
      selectPad(val){
        const list= this.ipadConfig.find(item=>{return item.value===val})
        this.$set(this.templateForm, 'device', list.label);
        this.$set(this.templateForm, 'window',list.window);
      }
    },
  }
</script>

<style scoped lang="less">
  .room-config-colors {
    width: 20px;
    height: 20px;
    float: left;
  }
</style>
